﻿using RSSReader.WebClient.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;

namespace RSSReader.WebClient
{
  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      AreaRegistration.RegisterAllAreas();
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
      BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

    protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
    {
      // Get a reference to the current User
      IPrincipal currentUser = HttpContext.Current.User;

      // If we are dealing with an authenticated forms authentication request
      if (currentUser.Identity.IsAuthenticated
          && currentUser.Identity.GetType() != typeof(UserIdentity))
      {
        // Create a CustomIdentity based on the FormsAuthenticationTicket           
        var identity = new UserIdentity(((FormsIdentity)currentUser.Identity).Ticket);

        // Create the CustomPrincipal
        var user = new GenericPrincipal(identity, null);

        // Attach the CustomPrincipal to HttpContext.User and Thread.CurrentPrincipal
        HttpContext.Current.User = user;
        Thread.CurrentPrincipal = user;
      }
    }
  }
}